<script>
import { insertTeacher } from '@/api/admin/teacher.js'
import teacherRules from '@/rules/teacherRules.js'
import { selectDepartmentOptions } from '@/api/authApi.js'
export default {
  props: ['modelValue'],
  emits: ['update:modelValue', 'resetData'],
  computed: {
    flag: {
      get() {
        return this.modelValue
      },
      set(nv) {
        this.$emit('update:modelValue', nv)
      },
    },
  },
  data() {
    return {
      teacherRules,
      departments: [],
      params: {
        department_id: '',
      },
      teacherData: {
        teacher_name: '',
        teacher_number: '',
        teacher_department_id: '',
      },
    }
  },

  methods: {
    async initDepartOptions() {
      this.departments = await selectDepartmentOptions(this.params)
    },
    remoteMethod(key) {
      this.params.department_id = key
      this.initDepartOptions()
    },
    async addNewTeacher() {
      await this.$refs.form.validate()
      await insertTeacher(this.teacherData)
      this.flag = false
      this.$emit('resetData')
    },
    resetFormData() {
      this.teacherData = {}
      this.$refs.form.resetFields()
    },
  },
  created() {
    this.initDepartOptions()
  },
}
</script>

<template>
  <el-dialog v-model="flag" title="新老师添加" width="600px" @closed="resetFormData">
    <el-form
      label-width="80px"
      :inline="false"
      ref="form"
      :model="teacherData"
      :rules="teacherRules"
    >
      <el-form-item label="老师名称" prop="teacher_name">
        <el-input type="text" v-model="teacherData.teacher_name"></el-input>
      </el-form-item>
      <el-form-item label="老师工号" prop="teacher_number">
        <el-input type="text" v-model="teacherData.teacher_number"></el-input>
      </el-form-item>
      <el-form-item label="院系" prop="teacher_department_id">
        <el-select
          clearable
          v-model="teacherData.teacher_department_id"
          filterable
          remote
          :remote-method="remoteMethod"
        >
          <el-option
            v-for="d in departments"
            :key="d.department_id"
            :value="d.department_id"
            :label="d.department_name"
          ></el-option>
        </el-select>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="$emit('update:modelValue', nv)">取消</el-button>
      <el-button type="primary" @click="addNewTeacher()">新增</el-button>
    </template>
  </el-dialog>
</template>
